package com.sheepone.distributor;

import com.lmax.disruptor.EventHandler;
import com.sheepone.distributor.event.WorkEvent;
import com.sheepone.distributor.thread.SafeThreadPool;

import java.util.concurrent.CountDownLatch;

/**
 * @author Miss.杨
 * @description
 * @since 2023-12-07 21:54
 */
public class WorkerLineHandler implements EventHandler<WorkEvent> {
    private final SafeThreadPool threadPool;

    public WorkerLineHandler(SafeThreadPool threadPool) {
        this.threadPool = threadPool;
    }

    @Override
    public void onEvent(WorkEvent event, long l, boolean b) throws Exception {
        CountDownLatch latch = new CountDownLatch(event.getListeners().size());
        try {
            event.getListeners().forEach(listener -> threadPool.submit(() -> {
                try {
                    listener.onEvent(event.getContext());
                } finally {
                    latch.countDown();
                }
            }));
            latch.await();
        } finally {
            event.finished();
        }
    }
}
